package com.example.online_exam_system.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;

/**
 * @author lianglong
 * @create 2021-11-25-20:16
 * @describe
 */


public class TimeUtil {
    public static long compareDate(String date1, String date2, int field) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        try {
            return compareDate(formater.parse(date1), formater.parse(date2), field);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static long compareDate(Date date1, Date date2, int field) {
        Calendar c1 = Calendar.getInstance();
        c1.setTime(date1);
        Calendar c2 = Calendar.getInstance();
        c2.setTime(date2);
        return compareCalendar(c1, c2, field);
    }

    public static long compareCalendar(Calendar c1, Calendar c2, int field) {
        long t1 = c1.getTimeInMillis();
        long t2 = c2.getTimeInMillis();
        switch(field) {
            case 1:
                return (long)(c1.get(1) - c2.get(1));
            case 2:
                return (long)(c1.get(1) * 12 - c2.get(1) * 12 + c1.get(2) - c2.get(2));
            case 3:
            case 4:
            case 6:
            case 7:
            case 8:
            case 9:
            case 11:
            default:
                return t1 - t2;
            case 5:
                int rawOffset = c1.getTimeZone().getRawOffset();
                return (t1 + (long)rawOffset) / 86400000L - (t2 + (long)rawOffset) / 86400000L;
            case 10:
                return t1 / 3600000L - t2 / 3600000L;
            case 12:
                return t1 / 60000L - t2 / 60000L;
            case 13:
                return t1 / 1000L - t2 / 1000L;
        }
    }
}

